<template>
  <div class="equipment-operation">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="运行记录编号">
          <el-input v-model="searchForm.operationNo" placeholder="请输入运行记录编号" clearable />
        </el-form-item>
        <el-form-item label="运行状态">
          <el-select v-model="searchForm.operationStatus" placeholder="请选择运行状态" clearable>
            <el-option 
              v-for="item in operationStatusList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作人员">
          <el-input v-model="searchForm.operator" placeholder="请输入操作人员" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增运行记录</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="operationNo" label="运行记录编号" width="150" />
        <el-table-column prop="deviceName" label="设备名称" min-width="150" />
        <el-table-column prop="deviceNo" label="设备编号" width="150" />
        <el-table-column prop="operationStatusName" label="运行状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.operationStatus)">
              {{ scope.row.operationStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="runHours" label="运行时长(小时)" width="120">
          <template #default="scope">
            {{ formatNumber(scope.row.runHours) }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人员" width="100" />
        <el-table-column prop="efficiency" label="运行效率(%)" width="120">
          <template #default="scope">
            {{ formatNumber(scope.row.efficiency) }}
          </template>
        </el-table-column>
        <el-table-column prop="energyConsumption" label="能耗" width="100">
          <template #default="scope">
            {{ formatNumber(scope.row.energyConsumption) }}
          </template>
        </el-table-column>
        <el-table-column prop="output" label="产量" width="100">
          <template #default="scope">
            {{ formatNumber(scope.row.output) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.endTime === null" 
              type="warning" 
              size="small" 
              @click="handleEnd(scope.row)"
            >
              结束运行
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select 
                v-model="form.deviceId" 
                placeholder="请选择设备" 
                style="width: 100%"
                filterable
                @change="handleDeviceChange"
              >
                <el-option 
                  v-for="item in deviceList" 
                  :key="item.id" 
                  :label="`${item.deviceName} (${item.deviceNo})`" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行状态" prop="operationStatus">
              <el-select v-model="form.operationStatus" placeholder="请选择运行状态" style="width: 100%">
                <el-option 
                  v-for="item in operationStatusList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作人员">
              <el-input v-model="form.operator" placeholder="请输入操作人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行时长(小时)">
              <el-input-number
                v-model="form.runHours"
                :precision="2"
                :step="0.5"
                :min="0"
                style="width: 100%"
                placeholder="请输入运行时长"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="运行效率(%)">
              <el-input-number
                v-model="form.efficiency"
                :precision="2"
                :step="1"
                :min="0"
                :max="100"
                style="width: 100%"
                placeholder="运行效率"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="能耗">
              <el-input-number
                v-model="form.energyConsumption"
                :precision="2"
                :step="1"
                :min="0"
                style="width: 100%"
                placeholder="能耗"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产量">
              <el-input-number
                v-model="form.output"
                :precision="2"
                :step="1"
                :min="0"
                style="width: 100%"
                placeholder="产量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="运行参数">
          <el-input
            v-model="form.operationParams"
            type="textarea"
            :rows="2"
            placeholder="请输入运行参数"
          />
        </el-form-item>
        <el-form-item label="运行数据">
          <el-input
            v-model="form.operationData"
            type="textarea"
            :rows="2"
            placeholder="请输入运行数据"
          />
        </el-form-item>
        <el-form-item label="异常情况">
          <el-input
            v-model="form.abnormalSituation"
            type="textarea"
            :rows="2"
            placeholder="请输入异常情况"
          />
        </el-form-item>
        <el-form-item label="处理措施">
          <el-input
            v-model="form.handlingMeasures"
            type="textarea"
            :rows="2"
            placeholder="请输入处理措施"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 运行记录详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="运行记录详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="operationDetail" class="operation-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运行记录编号">{{ operationDetail.operationNo }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ operationDetail.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ operationDetail.deviceNo }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getStatusTagType(operationDetail.operationStatus)">
              {{ operationDetail.operationStatusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(operationDetail.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(operationDetail.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="运行时长">{{ formatNumber(operationDetail.runHours) }}小时</el-descriptions-item>
          <el-descriptions-item label="操作人员">{{ operationDetail.operator || '无' }}</el-descriptions-item>
          <el-descriptions-item label="运行效率">{{ formatNumber(operationDetail.efficiency) }}%</el-descriptions-item>
          <el-descriptions-item label="能耗">{{ formatNumber(operationDetail.energyConsumption) }}</el-descriptions-item>
          <el-descriptions-item label="产量">{{ formatNumber(operationDetail.output) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(operationDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="运行参数" :span="2">{{ operationDetail.operationParams || '无' }}</el-descriptions-item>
          <el-descriptions-item label="运行数据" :span="2">{{ operationDetail.operationData || '无' }}</el-descriptions-item>
          <el-descriptions-item label="异常情况" :span="2">{{ operationDetail.abnormalSituation || '无' }}</el-descriptions-item>
          <el-descriptions-item label="处理措施" :span="2">{{ operationDetail.handlingMeasures || '无' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ operationDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 结束运行对话框 -->
    <el-dialog
      v-model="endDialogVisible"
      title="结束运行"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="endForm" :rules="endRules" ref="endFormRef" label-width="120px">
        <el-form-item label="运行时长(小时)" prop="runHours">
          <el-input-number
            v-model="endForm.runHours"
            :precision="2"
            :step="0.5"
            :min="0"
            style="width: 100%"
            placeholder="请输入运行时长"
          />
        </el-form-item>
        <el-form-item label="运行效率(%)" prop="efficiency">
          <el-input-number
            v-model="endForm.efficiency"
            :precision="2"
            :step="1"
            :min="0"
            :max="100"
            style="width: 100%"
            placeholder="运行效率"
          />
        </el-form-item>
        <el-form-item label="能耗">
          <el-input-number
            v-model="endForm.energyConsumption"
            :precision="2"
            :step="1"
            :min="0"
            style="width: 100%"
            placeholder="能耗"
          />
        </el-form-item>
        <el-form-item label="产量">
          <el-input-number
            v-model="endForm.output"
            :precision="2"
            :step="1"
            :min="0"
            style="width: 100%"
            placeholder="产量"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="endDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEndSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { equipmentApi } from '@/api/equipment/equipment'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "equipment_operation",
  data() {
    return {
      // 搜索表单
      searchForm: {
        operationNo: '',
        operationStatus: '',
        operator: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 表单数据
      form: {
        deviceId: null,
        operationStatus: null,
        startTime: '',
        endTime: '',
        runHours: null,
        operator: '',
        operationParams: '',
        operationData: '',
        abnormalSituation: '',
        handlingMeasures: '',
        efficiency: null,
        energyConsumption: null,
        output: null,
        remark: ''
      },
      // 表单验证规则
      rules: {
        deviceId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        operationStatus: [
          { required: true, message: '请选择运行状态', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ]
      },
      // 表单引用
      formRef: null,
      // 编辑模式
      isEdit: false,
      // 编辑的运行记录ID
      editId: null,
      // 详情对话框
      detailDialogVisible: false,
      // 运行记录详情数据
      operationDetail: null,
      // 结束运行对话框
      endDialogVisible: false,
      // 结束运行表单
      endForm: {
        runHours: null,
        efficiency: null,
        energyConsumption: null,
        output: null
      },
      // 结束运行验证规则
      endRules: {
        runHours: [
          { required: true, message: '请输入运行时长', trigger: 'blur' }
        ],
        efficiency: [
          { required: true, message: '请输入运行效率', trigger: 'blur' }
        ]
      },
      // 结束运行表单引用
      endFormRef: null,
      // 当前操作的运行记录ID
      currentOperationId: null,
      // 运行状态列表
      operationStatusList: [
        { value: 1, label: '开机' },
        { value: 2, label: '运行中' },
        { value: 3, label: '停机' },
        { value: 4, label: '故障' }
      ],
      // 设备列表
      deviceList: []
    }
  },
  mounted() {
    this.loadTableData()
    this.loadDeviceList()
  },
  methods: {
    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          current: this.pagination.current,
          size: this.pagination.size
        }
        const res = await equipmentApi.getDeviceOperationPage(params)
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        }
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 加载设备列表
    async loadDeviceList() {
      try {
        const res = await equipmentApi.getDevicePage({ current: 1, size: 1000 })
        if (res.code === 200) {
          this.deviceList = res.data.records
        }
      } catch (error) {
        console.error('加载设备列表失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        operationNo: '',
        operationStatus: '',
        operator: ''
      }
      this.handleSearch()
    },

    // 新增运行记录
    handleAdd() {
      this.isEdit = false
      this.editId = null
      this.dialogTitle = '新增运行记录'
      this.form = {
        deviceId: null,
        operationStatus: null,
        startTime: '',
        endTime: '',
        runHours: null,
        operator: '',
        operationParams: '',
        operationData: '',
        abnormalSituation: '',
        handlingMeasures: '',
        efficiency: null,
        energyConsumption: null,
        output: null,
        remark: ''
      }
      this.dialogVisible = true
    },

    // 编辑运行记录
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑运行记录'
      this.form = {
        deviceId: row.deviceId,
        operationStatus: row.operationStatus,
        startTime: row.startTime,
        endTime: row.endTime,
        runHours: row.runHours,
        operator: row.operator,
        operationParams: row.operationParams,
        operationData: row.operationData,
        abnormalSituation: row.abnormalSituation,
        handlingMeasures: row.handlingMeasures,
        efficiency: row.efficiency,
        energyConsumption: row.energyConsumption,
        output: row.output,
        remark: row.remark
      }
      this.dialogVisible = true
    },

    // 保存运行记录
    async handleSave() {
      try {
        await this.$refs.formRef.validate()
        
        if (this.isEdit) {
          // 编辑
          const res = await equipmentApi.updateDeviceOperation(this.editId, this.form)
          if (res.code === 200) {
            ElMessage.success('运行记录更新成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增
          const res = await equipmentApi.addDeviceOperation(this.form)
          if (res.code === 200) {
            ElMessage.success('运行记录创建成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    // 查看详情
    async handleView(row) {
      try {
        const res = await equipmentApi.getDeviceOperationById(row.id)
        if (res.code === 200) {
          this.operationDetail = res.data
          this.detailDialogVisible = true
        } else {
          ElMessage.error(res.message || '获取运行记录详情失败')
        }
      } catch (error) {
        console.error('获取运行记录详情失败:', error)
        ElMessage.error('获取运行记录详情失败')
      }
    },

    // 结束运行
    handleEnd(row) {
      this.currentOperationId = row.id
      this.endForm = {
        runHours: null,
        efficiency: null,
        energyConsumption: null,
        output: null
      }
      this.endDialogVisible = true
    },

    // 保存结束运行
    async handleEndSave() {
      try {
        await this.$refs.endFormRef.validate()
        
        const res = await equipmentApi.endOperation(this.currentOperationId, this.endForm)
        if (res.code === 200) {
          ElMessage.success('运行已结束')
          this.endDialogVisible = false
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '结束运行失败')
        }
      } catch (error) {
        console.error('结束运行失败:', error)
      }
    },

    // 删除运行记录
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确定要删除该运行记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await equipmentApi.deleteDeviceOperation(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    // 设备选择变化
    handleDeviceChange(deviceId) {
      // 可以在这里添加设备相关的逻辑
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTableData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTableData()
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },

    // 格式化数字
    formatNumber(num) {
      if (num === null || num === undefined) return '0.00'
      return Number(num).toFixed(2)
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case 1:
          return 'info'
        case 2:
          return 'success'
        case 3:
          return 'warning'
        case 4:
          return 'danger'
        default:
          return 'info'
      }
    }
  }
}
</script>

<style scoped>
.equipment-operation {
  padding: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.operation-detail .el-descriptions {
  margin-bottom: 20px;
}
</style>
